package com.ccc.influxdb.config;

import com.influxdb.LogLevel;
import com.influxdb.client.InfluxDBClient;
import com.influxdb.client.InfluxDBClientFactory;
import com.influxdb.client.domain.Permission;
import com.influxdb.client.domain.PermissionResource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 配置类
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({InfluxDBProperties.class})
public class InfluxDBConfig {

    @Autowired
    private InfluxDBProperties properties;

    /**
     * InfluxDB操作数据客户端
     *
     * @return {@link InfluxDBClient}
     * @date 2023/3/3 9:51
     * @author superC
     */
    @Bean
    public InfluxDBClient influxDBClient() {
        InfluxDBClient client = InfluxDBClientFactory.create(properties.getUrl(), properties.getToken().toCharArray());
        client.setLogLevel(LogLevel.BASIC);
        return client;
    }

    /**
     * InfluxDB操作平台客户端
     *
     * @return {@link InfluxDBClient}
     * @date 2023/3/3 9:51
     * @author superC
     */
    @Bean
    public InfluxDBClient platformClient() {
        InfluxDBClient client = null;
        try {
            client = InfluxDBClientFactory.create(properties.getUrl(), findToken2AuthOrgs().toCharArray());
            client.setLogLevel(LogLevel.BASIC);
        } catch (Exception e) {
            log.error("get root's Token error! \r\n异常记录：", e);
        }
        return client;
    }

    /**
     * 获取拥有orgs权限的token（若有多个取找到的第一个）
     */
    private String findToken2AuthOrgs() throws Exception {
        InfluxDBClient client = InfluxDBClientFactory.create(properties.getUrl(),
                properties.getUsername(), properties.getPassword().toCharArray());
        String token = client.getAuthorizationsApi()
                .findAuthorizations()
                .stream()
                .filter(authorization -> authorization.getPermissions().stream()
                        .map(Permission::getResource)
                        .anyMatch(resource ->
                                resource.getType().equals(PermissionResource.TYPE_ORGS) &&
                                        resource.getId() == null &&
                                        resource.getOrgID() == null))
                .findFirst()
                .orElseThrow(IllegalStateException::new).getToken();
        client.close();
        log.info("roots token is {}", token);
        return token;
    }
}
